from functools import cache
from typing import *
from math import inf


class Solution:
    def minArraySum(self, nums: List[int], k: int, op1: int, op2: int) -> int:
        @cache
        def f(i, op1, op2):
            if i == -1:
                return 0
            a1 = nums[i] + f(i - 1, op1, op2)
            a2 = a3 = a4 = a5 = inf
            if op1 > 0:
                a2 = (nums[i] + 1) // 2 + f(i - 1, op1 - 1, op2)
            if op2 > 0 and nums[i] >= k:
                a3 = (nums[i] - k) + f(i - 1, op1, op2 - 1)
            if op1 > 0 and op2 > 0 and (nums[i] + 1) // 2 >= k:
                a4 = ((nums[i] + 1) // 2 - k) + f(i - 1, op1 - 1, op2 - 1)
            if op1 > 0 and op2 > 0 and nums[i] >= k:
                a5 = (nums[i] - k + 1) // 2 + f(i - 1, op1 - 1, op2 - 1)
            return min(a1, a2, a3, a4, a5)

        return f(len(nums) - 1, op1, op2)
